package com.wang.demo.application.handler;

import com.wang.demo.service.factory.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>两种退出方式
 *  <ul>
 *      <li>正常断开连接退出 channelInactive</li>
 *      <li>异常断开(直接关闭客户端)exceptionCaught</li>
 *  </ul></p>
 * @author: Jeffrey
 * @date: 2022/01/21/11:13
 * @description:
 */
@ChannelHandler.Sharable
@Slf4j
public class QuitHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        /*把Channel 从会话管理器中移除*/
        SessionFactory.getSession().unbind(ctx.channel());
        log.debug("{}已经断开",ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        SessionFactory.getSession().unbind(ctx.channel());
        log.debug("{}异常断开 异常是{}",ctx.channel(),cause.getMessage());
    }
}
